<template>
  <el-dialog
    class="column-config"
    title="自定义列"
    :lock-scroll="false"
    :visible.sync="customColumnVisible"
    width="70%"
  >
    <div class="tips">
      勾选需要显示的列，拖动列名进行排序，自定义字段宽度，不填代表自动宽度。
    </div>
    <br />
    <el-table
      ref="customColumnTable"
      class="erp-page-table-column-config-table"
      :data="columnConfigData"
      border
      stripe
      row-key="label"
      :header-cell-style="headerCellStyle"
      @selection-change="handleSelectionChange"
      @select="handleSelect"
      @select-all="handleSelectAll"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
        :selectable="customColumnSelect"
      />
      <el-table-column
        :label="$t('common.erp.config.columnName')"
        align="left"
      >
        <template slot-scope="scope">
          {{ scope.row.label }}
        </template>
      </el-table-column>
      <el-table-column
        width="120"
        :label="$t('common.erp.config.fixed')"
        align="center"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.fixed"
            placeholder="请选择"
          >
            <el-option
              v-for="item in fixedList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        width="150"
        :label="$t('common.erp.config.width')"
        align="center"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.width"
            style="width: 100px"
            type="number"
          /> <span>px</span>
        </template>
      </el-table-column>
      <el-table-column
        width="50"
        :label="$t('common.operation')"
        align="center"
      >
        <template slot-scope="scope">
          <div class="column-move">
            <i
              class="el-icon-rank draggable-icon"
              style="cursor: pointer;font-size: 16px;"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer">
      <el-button
        type="primary"
        @click="saveCustomColumn"
      >
        {{ $t('common.save') }}
      </el-button>
      <el-button @click="resetCustomColumn">
        {{ $t('common.reset') }}
      </el-button>
      <el-button @click="customColumnVisible = false">
        {{ $t('common.cancel') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import Vue from 'vue';
import {Dialog, Input, OptionGroup, Select, Table, TableColumn, Option, Button} from "element-ui";
import {cloneJson, getStorage, removeStorage, setStorage, toast} from "../../../utils";
import Sortable from "sortablejs";

Vue.use(Dialog);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Input);
Vue.use(Select);
Vue.use(Option);
Vue.use(OptionGroup);
Vue.use(Button);
/**
 * 自定义列组件
 * @author maolin
 */
export default {
  name: "ColumnConfig",
  props: {
    /**
     * 操作按钮浮动
     * @public
     */
    operationFixed: {
      type: String,
      default: 'right'
    },
    /**
     * 字段列表
     * @public
     */
    fields: {
      type: Array,
      default () {
        return [];
      }
    },
    /**
     * 类型
     * @public
     */
    type: {
      type: String,
      default: 'list'
    },
    /**
     * 操作栏宽度
     * @public
     */
    operationWidth: {
      type: Number,
      default: 100
    },
    /**
     * 组件名称，用于保存到缓存，必须要唯一否则会覆盖
     * @public
     */
    name: {
      type: String,
      default () {
        let name = '';
        if(this.$route && this.$route.name) {
          name = this.$route.name + '_FIELDS';
        }
        return name;
      }
    },
    /**
     * 表格头部样式
     * @public
     */
    headerCellStyle: {
      type: Object,
      default () {
        return {
          color: '#fff',
          background: 'var(--primary-color)'
        };
      }
    }
  },
  data () {
    return {
      customColumnVisible: false,
      fixedList: [
        {name: this.$t('common.erp.config.noneFixed'), value: null},
        {name: this.$t('common.erp.config.leftFixed'), value: 'left'},
        {name: this.$t('common.erp.config.rightFixed'), value: 'right'},
        {name: this.$t('common.erp.config.fixed'), value: true},
      ],
      columnConfigData: []
    };
  },
  computed: {
  },
  watch: {
    customColumnVisible (visible) {
      if(visible){
        this.$nextTick(() => {
          if (this.columnConfigData) {
            this.columnConfigData.forEach(row => {
              if(row.checked || row.checked === undefined) {
                this.$refs.customColumnTable.toggleRowSelection(row, true);
              }
            });
          }
          this.rowDrop();
        });
      }

    }
  },
  mounted() {
    this.getColumnConfigData();
  },
  methods: {
    /**
     * 自定义选择列，disabled的列无法进行选择
     * @private
     * @param row
     * @param index
     * @returns {number}
     */
    customColumnSelect (row, index) {
      if(row.disabled){
        return 0;
      } else {
        return 1;
      }
    },
    /**
     * 重置自定义列
     * @private
     */
    resetCustomColumn () {
      let data = this.fields || [];
      data = data.concat([
        {label: this.$t('common.operation'), prop: '__operation', type: 'operation', fixed: this.operationFixed, width: this.operationWidth, disabled: true, checked: true}
      ]);
      this.columnConfigData = data;
      removeStorage(this.name);
      this.translateData();
      toast({
        message: this.$t('common.resetSuccess'),
        type: 'success',
      });
      this.customColumnVisible = false;

    },
    /**
     * 拖拽表格初始化
     * @private
     */
    rowDrop() {
      let _this = this;
      const table = document.querySelector('.erp-page-table-column-config-table tbody');
      Sortable.create(table, {
        sort: true,
        handle: '.column-move',
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen',
        onEnd({ newIndex, oldIndex }) {
          _this.columnConfigData.splice(newIndex, 0, _this.columnConfigData.splice(oldIndex, 1)[0]);
        },
      });
    },
    /**
     * 保存自定义列
     * @private
     */
    saveCustomColumn () {
      let columnConfigData = this.columnConfigData;
      setStorage(this.name, JSON.stringify(columnConfigData));
      this.translateData();
      toast({
        message: this.$t('common.saveSuccess'),
        type: 'success',
      });
      this.customColumnVisible = false;
    },
    /**
     * 列变化
     * @private
     */
    translateData () {
      let data = cloneJson(this.columnConfigData);
      this.$emit('change', data);
    },
    /**
     * @private
     * @param data
     */
    handleSelectionChange (data) {
    },
    /**
     * 监听选中列
     * @private
     * @param data
     * @param row
     */
    handleSelect (data,row) {
      let prop = row.prop;
      let columnConfigData = this.columnConfigData;
      if(columnConfigData && columnConfigData.length > 0) {
        for (let i in columnConfigData) {
          if (prop === columnConfigData[i].prop) {
            if(columnConfigData[i].checked !== undefined && !columnConfigData[i].checked){
              columnConfigData[i].checked = true;
            } else {
              columnConfigData[i].checked = false;
            }
          }
        }
      }
      this.columnConfigData = columnConfigData;
    },
    /**
     * 全选列
     * @private
     * @param selection
     */
    handleSelectAll (selection) {
      let columnConfigData = this.columnConfigData;
      if(columnConfigData && columnConfigData.length > 0) {
        for (let i in columnConfigData) {
          let checked = false;
          if(selection && selection.length > 0) {
            for (let j in selection) {
              if(columnConfigData[i].prop === selection[j].prop) {
                checked = true;
                break;
              }
            }
          }
          columnConfigData[i].checked = checked;
        }
      }
      this.columnConfigData = columnConfigData;
    },
    /**
     * 获取自定义列数据
     */
    getColumnConfigData () {
      let data = null;
      if (this.type === 'list') {
        data = getStorage(this.name);
      }
      if(!data) {
        data = cloneJson(this.fields) || [];
        data = data.concat([
          {label: this.$t('common.operation'), prop: '__operation', type: 'operation', fixed: 'right', width: this.operationWidth, disabled: true, checked: true}
        ]);
      } else {
        try{
          data = JSON.parse(data);
        }catch (e) {
          data = [];
        }
      }
      this.columnConfigData = data;
      this.translateData();

    }
  }
};
</script>

<style lang="scss" scoped>
    .column-config{
        .tips{
            font-size:12px;
            color: #838a9d;
        }
        ::v-deep{
            .el-dialog__body{
                padding: 0 20px 30px 20px;
            }
        }
        .footer{
            margin-top: 10px;
            text-align: right;
        }
    }
    .sortable-ghost{
        background-color: #fdecce;
        height: 30px;
        width: 100%;
        border: 1px dashed #ccc;
    }
    .sortable-chosen{
        background-color: #fdecce;
        height: 30px;
        width: 100%;
        border: 1px dashed #ccc;
    }
    .erp-page-table-column-config-table{
        tbody{
            ::v-deep{
                .el-table tr{
                    cursor: move;
                }
            }
        }
    }
    .sortable-ghost{
        background-color: yellow;
    }

</style>
